package world3d;

import java.util.ArrayList;

import javax.media.j3d.Appearance;
import javax.media.j3d.GeometryArray;
import javax.media.j3d.Material;
import javax.media.j3d.QuadArray;
import javax.media.j3d.Shape3D;
import javax.media.j3d.Texture2D;
import javax.media.j3d.TextureAttributes;
import javax.vecmath.Point3f;
import javax.vecmath.TexCoord2f;
import javax.vecmath.Vector3f;

import com.sun.j3d.utils.image.TextureLoader;

public class TexturedPlane extends Shape3D {
	
	public static final int TOP = 0, BOTTOM = 1, RIGHT = 2, LEFT = 3;
	
	private QuadArray plane;
	private int nPoints;
	
	private int orientation;
	
	public TexturedPlane(ArrayList coords, Vector3f normal, String file, int orientation){
		nPoints = coords.size();
		System.out.println(nPoints);
		plane = new QuadArray(nPoints, 
				GeometryArray.COORDINATES |
				GeometryArray.TEXTURE_COORDINATE_2 |
				GeometryArray.NORMALS);
		
		this.orientation = orientation;
		createGeometry(coords, normal);
		loadAppearance(file);
	}
	
	private void createGeometry(ArrayList coords, Vector3f normal){
		Point3f[] ps = new Point3f[nPoints];
		coords.toArray(ps);
		plane.setCoordinates(0, ps);
		
		TexCoord2f[] tc = new TexCoord2f[nPoints];
		
		for(int i = 0; i < nPoints; i += 4){
			tc[i + (3 + orientation) % 4] = new TexCoord2f(0.0f, 1.0f);
			tc[i + (2 + orientation) % 4] = new TexCoord2f(0.0f, 0.0f);
			tc[i + (1 + orientation) % 4] = new TexCoord2f(1.0f, 0.0f);
			tc[i + (orientation) % 4] = new TexCoord2f(1.0f, 1.0f);
		}
		
		plane.setTextureCoordinates(0, 0, tc);
		for(int i =0; i< nPoints; i++)
			plane.setNormal(i, normal);
		
		setGeometry(plane);
	}
	
	private void loadAppearance(String file){
		Appearance app = new Appearance();
		
		TextureAttributes ta = new TextureAttributes();
		ta.setTextureMode(TextureAttributes.MODULATE);
		app.setTextureAttributes(ta);
		
		TextureLoader loader = new TextureLoader(file, null);
		Texture2D texture = (Texture2D)(loader.getTexture());
		app.setTexture(texture);
		
		Material mat = new Material();
		mat.setLightingEnable(true);
		app.setMaterial(mat);
		setAppearance(app);
	}
}
